package cl.scene.libbencode;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by IntelliJ IDEA.
 * User: Patricio
 * Date: 23-11-2010
 * Time: 10:00:18 PM
 */
public class IntegerValue extends NativeType {
    private long value;

    public IntegerValue(int i) {
        this.value = i;
    }

    public IntegerValue(InputStream is) throws IOException {
        byte[] b = new byte[1];
        String strValue = "";
        int status = BencodeParser.READING_SIGN;
        boolean negative = false;
        while(is.read(b) >= 0) {
            if(b[0] == '-' && status == BencodeParser.READING_SIGN) {
                status = BencodeParser.READING_INTEGER_VALUE;
                negative = true;
            } else if(b[0] > 47 && b[0] < 59) {
                strValue = strValue.concat(new String(b));
                 status = BencodeParser.READING_INTEGER_VALUE;
            } else if(b[0] == 'e' && status == BencodeParser.READING_INTEGER_VALUE) {
                value = Long.parseLong(strValue);
                value = negative ? value * -1 : value;
                break;
            } else {
                throw new IOException("Malformed stream!");
            }
        }

        System.out.println("Integer -> " + value);
    }

    public void encodeAndWrite(OutputStream o) throws IOException {
        o.write('i');
        o.write(Long.toString(value).getBytes());
        o.write('e');
    }

    public long getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
}
